/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

// 引入 lodash 库，用于数据处理和操作
const _ = require('lodash')
// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '..')
// helpers 目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')

// 计算准确统计
const { calcAccuracySummary } = require(path.join(HELPERS_DIR, 'calcAccuracySummary.js'))

const insertData = async (connection, groupAccuracySummary, insert_table_name) => {
  const batchSize = 100 // 每批插入的数据量
  const groupAccuracySummaryValues = groupAccuracySummary.map((item) => [
    item.history_result_id,
    item.time,
    item.number,
    item.group_name,
    item.group_type,
    item.sub_index,
    item.sub_array,
    item.accuracy,
    item.accuracyArray,
    item.correctCount,
    item.incorrectCount,
    item.accuracyRate,
    item.maxConsecutiveCorrect,
    item.maxConsecutiveIncorrect,
    item.consecutiveCorrectSegments,
    item.consecutiveIncorrectSegments,
    item.avgConsecutiveCorrect,
    item.avgConsecutiveIncorrect,
    item.currentConsecutiveCorrect,
    item.currentConsecutiveIncorrect
  ])
  // console.log(groupAccuracySummaryValues)
  try {
    await connection.beginTransaction()
    for (let i = 0; i < groupAccuracySummaryValues.length; i += batchSize) {
      const batch = groupAccuracySummaryValues.slice(i, i + batchSize)
      await connection.query(
        `INSERT INTO ${insert_table_name} (history_result_id, time, number, group_name, group_type, sub_index, sub_array, accuracy, accuracy_array, correct_count, incorrect_count, accuracy_rate, max_consecutive_correct, max_consecutive_incorrect, consecutive_correct_segments, consecutive_incorrect_segments, avg_consecutive_correct, avg_consecutive_incorrect, current_consecutive_correct, current_consecutive_incorrect) VALUES ?`,
        [batch]
      )
    }
    await connection.commit()
    // console.log(`批量插入完成：${groupAccuracySummaryValues.length} 条`)
  } catch (err) {
    await connection.rollback()
    console.error('批量插入时出错:', err)
  }
}

// daily_group_accuracy_summary
const insertDailyGroupAccuracySummary = async (
  pool,
  groupAccuracyMap,
  history_results,
  read_table_name,
  insert_table_name
) => {
  // 获取连接池的连接
  const connection = await pool.getConnection()

  // 开始事务
  await connection.beginTransaction()

  try {
    for (const [index, element] of history_results.entries()) {
      // 第一个元素，处理并设置 accuracy 为 1
      const [itemGroupAccuracy] = await connection.query(
        `SELECT * FROM ${read_table_name} WHERE history_result_id = ?`,
        [element.id]
      )

      if (itemGroupAccuracy.length !== 15754) {
        console.error('数据异常 itemGroupAccuracy.length !== 15754:', itemGroupAccuracy.length)
      }

      // 第一个元素，处理并设置 accuracy 为 1
      const itemGroupAccuracyArray = itemGroupAccuracy.map((item, itemIndex) => {
        const tempAccuracyData = groupAccuracyMap[item.group_name].slice(0, index + 1)
        const stats = calcAccuracySummary(tempAccuracyData)
        return {
          ..._.omit(item, ['id']),
          history_result_id: element.id,
          ...stats,
          accuracyArray: JSON.stringify(tempAccuracyData),
          sub_array: JSON.stringify(item.sub_array)
        }
      })
      await insertData(connection, itemGroupAccuracyArray, insert_table_name)
      // 成功输出
      // console.log(`${element.id} 插入完成`)
    }

    // 提交事务
    await connection.commit()
  } catch (err) {
    // 回滚事务
    await connection.rollback()
    console.error('处理过程中发生错误:', err)
  } finally {
    // 释放连接
    connection.release()
  }

  console.log('完成')
}

module.exports = { insertDailyGroupAccuracySummary }
